<!-- 商品分类 -->
<template>
	<view>
		<Searchbar v-model="keywords" placeholder="分类名称" />
		<TransverseTabbar :height="40" :nav1="nav1" :nav2="nav2" @change-tab1="changeTab1" @change-tab2="changeTab2" />
	</view>
</template>

<script>
	import Searchbar from '../common/Searchbar.vue'
	import TransverseTabbar from '../common/TransverseTabbar.vue'
	
	export default {
		components:{
			Searchbar,
			TransverseTabbar,
		},
		data() {
			return {
				currentIndex1: 0,
				currentIndex2: 0,
				nav1: [],
				nav2: [],
				keywords: '',
			}
		},
		watch:{
			keywords(v) {
				if(v) {
					this.filterNav()
				} else {
					this.getList1()
				}
			}
		},
		onShow() {
			this.getList1()
		},
		methods: {
			// 获取商品全部类目
			getList1() {
				this.$http.post(this.$api.shop_tabs_1).then(result => {
					if(result.code === 200) {
						this.nav1 = result.data;
						if(Array.isArray(this.nav1) && this.nav1.length > 0) {
							this.changeTab1(0)
						}
					}
				})
			},
			changeTab1(index) {
				this.currentIndex1 = index
				this.nav2 = this.nav1[index] ? this.nav1[index].mallProductCategories : []
			},
			changeTab2(index) {
				this.currentIndex2 = index
				uni.navigateTo({
					url: `../list/list?nav1_id=${this.nav1[this.currentIndex1].id}&nav2_id=${this.nav2[index].id}`
				})
			},
			// 根据二级分类名称筛选
			filterNav() {
				const list = this.nav1.map(item1 => {
					item1.mallProductCategories = Array.isArray(item1.mallProductCategories) ? item1.mallProductCategories.filter(item2 => item2.name.includes(this.keywords)) : []
					return item1
				}).filter(i => i.mallProductCategories.length > 0)
				this.nav1 = list
				if(list.length > 0) {
					this.changeTab1(0)
				} else {
					this.nav2 = []
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	
</style>
